package com.wlj.web.controller;


import com.wlj.entity.FileInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
public class FileController {

    private  String folder="";

    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {

        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename()); //上传的原始文件名
        System.out.println(file.getSize());

        //使用getRealPath()获取的是tomcat的临时缓存文件目录
//        String realPath = request.getSession().getServletContext().getRealPath("/tmp");
//        if(!FileUtil.exist(realPath)){
//            FileUtil.mkdir(realPath);
//        }

        File localFile = new File(folder, System.currentTimeMillis() + ".text");
        file.transferTo(localFile);

        return new FileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //把"流"声明在try的括号里，不用手动关闭"流",会自动关闭
        try(
                InputStream inputStream=new FileInputStream(new File(folder,id+".text"));
                OutputStream outputStream = resp.getOutputStream();
                ){
            resp.setContentType("application/x-download");
            resp.setHeader("Content-Disposition","attachment;filename-test.text");

            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        }
    }
}
